import {
  Container, Table, TableBody, TableCell, TableContainer,
  TableHead, TableRow, Typography
} from '@mui/material';
import { useNavigate } from 'react-router-dom';
import React, { useState, useEffect } from 'react';

// 导入封装好的接口函数
import { getSeedList, searchSeedByName } from '../api/seed';  // 新增 searchSeedByName

const SeedList = ({ category, first, second, third, fourth, name, type }) => {
  const navigate = useNavigate();
  const [seeds, setSeeds] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchType,setSearchType] = useState({
    category: category,
    first: first,
    second: second,
    third: third,
    fourth: fourth
  });
  const [sortField, setSortField] = useState('downloads');
  const [sortDirections, setSortDirections] = useState({
    size: 'desc',
    downloads: 'desc',
    cost: 'desc'
  });

  const handleSort = (field) => {
    const newDirection = sortDirections[field] === 'asc' ? 'desc' : 'asc';
    setSortDirections(prev => ({
      ...prev,
      [field]: newDirection
    }));
    setSortField(field);
  };

  const getArrow = (field) => {
    return sortDirections[field] === 'asc' ? '▲' : '▼';
  };

  useEffect(() => {
    const fetchSeeds = async () => {
      setLoading(true);
      setError(null);
      try {
        let response;
        if (name && name.trim() !== '') {
          // 如果有name搜索，调用根据名字搜索接口
          console.log("name搜索",name);
          response = await searchSeedByName(name,type);
          response = response.content;
        } else {
          // 只传category，获取所有该类别种子
          response = await getSeedList(category );
          // response = await getSeedList();
        }
        console.log(response);
        setSeeds(response);
        // setSeeds(response.data);

      } catch (err) {
        console.log(err)
        setError('获取数据失败');
      } finally {
        setLoading(false);
      }
    };
    fetchSeeds();
  }, [category, name]);

  // 前端基于first, second, third, fourth进行筛选
  const filteredSeeds = seeds.filter(seed => {
     if (category && seed.type !==category) return false;
    if (first && seed.firsttype !== first) return false;
    if (second && seed.secondtype !== second) return false;
    if (third && seed.thirdtype !== third) return false;
    if (fourth && seed.fourthtype !== fourth) return false;
    return true;
  });

  const sortedSeeds = [...filteredSeeds].sort((a, b) => {
    let valA = a[sortField];
    let valB = b[sortField];

    if (sortField === "size") {
      const toMB = (size) => {
        const num = parseFloat(size);
        if (size.toUpperCase().includes("GB")) return num * 1024;
        if (size.toUpperCase().includes("MB")) return num;
        return num;
      };
      valA = toMB(valA);
      valB = toMB(valB);
    }

    if (typeof valA === 'string') valA = valA.toLowerCase();
    if (typeof valB === 'string') valB = valB.toLowerCase();

    if (valA < valB) return sortDirections[sortField] === 'asc' ? -1 : 1;
    if (valA > valB) return sortDirections[sortField] === 'asc' ? 1 : -1;
    return 0;
  });

  const handleClick = (id) => {
    navigate(`/seed/${id}`);
  };

  return (
    <div className='seedList'>
      <Container maxWidth="lg" sx={{ py: 4 }}>
        <Typography variant="h5" gutterBottom>种子列表</Typography>
        {loading ? (
          <Typography>加载中...</Typography>
        ) : error ? (
          <Typography color="error">{error}</Typography>
        ) : (
          <TableContainer>
            <Table>
              <TableHead>
                <TableRow>
                  <TableCell>资源名称</TableCell>
                  <TableCell align="right" onClick={() => handleSort('size')} style={{ cursor: 'pointer' }}>
                    大小 {getArrow('size')}
                  </TableCell>
                  <TableCell align="right" onClick={() => handleSort('downloads')} style={{ cursor: 'pointer' }}>
                    下载量 {getArrow('downloads')}
                  </TableCell>
                  <TableCell align="right" onClick={() => handleSort('cost')} style={{ cursor: 'pointer' }}>
                    价格 {getArrow('cost')}
                  </TableCell>
                </TableRow>
              </TableHead>
              <TableBody>
                {sortedSeeds.length > 0 ? (
                  sortedSeeds.map((seed) => (
                    <TableRow
                      key={seed.id}
                      onClick={() => handleClick(seed.id)}
                      sx={{ cursor: "pointer", '&:hover': { backgroundColor: "#f0f0f0" } }}
                    >
                      <TableCell>{seed.name||seed.fileName}</TableCell>
                      <TableCell align="right">{seed.formattedSize}</TableCell>
                      <TableCell align="right">{seed.downloads}</TableCell>
                      <TableCell align="right">{seed.cost||'免费'}</TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={4} align="center">没有符合条件的种子</TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </TableContainer>
        )}
      </Container>
    </div>
  );
};

export default SeedList;
